package saiboten.actions;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

import saiboten.ChannelAction;

public class GjettPlugin implements ChannelAction {
	
	String currentQuestion;
	String currentAnswer;
	
	
	final String URL = "quiz.txt";
	
	Map<String,String> quiz;
	Map<String,Integer> points;
	
	public void reloadQuestions(String url) {
		quiz = new HashMap<String,String>();
		points = new HashMap<String,Integer>();
		
		try {
			
			Scanner scanner = new Scanner(new File(url));
			while(scanner.hasNextLine()) {
				String line = scanner.nextLine();
				quiz.put(line.split("\\|")[0].trim(),line.split("\\|")[1].trim().toLowerCase());
			}
		} catch (FileNotFoundException e) {
			System.out.println("Fuck!");
		}
	}
	
	private void newQuestion(List<String> results, String channel) {
		List<String> spsm = new ArrayList<String>(); 
			spsm.addAll(quiz.keySet());
		currentQuestion = spsm.get((int)(Math.random()*spsm.size()));
		currentAnswer = quiz.get(currentQuestion);
		results.add("Nytt spsm: " + currentQuestion);
	}
	
	public List<String> action(List<String> results, String channel, String sender,
			String message) {
		if(message.equals("!quizreload"))
			reloadQuestions(URL);
		else if(message.equals("!quizstart"))
			newQuestion(results, channel);
		else if(message.equals("!quizrepeat"))
			results.add("Spsm: " + currentQuestion);
		else if(message.equals("!quizhigh"))
			writeHighscore(results, channel);
		else if(message.toLowerCase().equals(currentAnswer)) {
			results.add("Helt riktig! Et poeng til deg.");
			if(points.containsKey(sender))
				points.put(sender, points.get(sender) + 1);
			else
				points.put(sender, 1);
			newQuestion(results, channel);
		}
		return results;
	}
	
	private void writeHighscore(List<String> results, String channel) {
		for(String player : points.keySet())
			results.add(player + ":" + points.get(player));
		
	}

}
